package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.constants.MQConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class OrderDelayListener {
    private final IOrderService orderService;

    private final PayClient payClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.DELAY_ORDER_QUEUE_NAME,
                    arguments = @Argument(name = "x-queue-mode",value = "lazy")),
            exchange = @Exchange(name = MQConstants.DELAY_EXCHANGE_NAME,delayed = "true"),
            key = {MQConstants.DELAY_ORDER_KEY}
    ))
    public void listenOrder(Long orderId){
        //1.查询业务订单状态
        Order order = orderService.getById(orderId);
        if(order == null || order.getStatus() == 2){
            return ;
        }
        //2.查询支付订单状态
        PayOrderDTO payOrderDTO = payClient.queryByOrderId(orderId);
        if(payOrderDTO != null && payOrderDTO.getStatus() == 3){
            //3.支付订单为已支付
            //4.修改业务订单
            orderService.markOrderPaySuccess(orderId);
        }else {
            //5.支付订单为未支付
            //6.取消订单并扣减库存
            orderService.cancelOrder(orderId);
        }


    }
}
